<template>
  <div class="container">
    <div class="headerDate">
      <div class="title_case">
        <el-icon @click="handleLeft"><ArrowLeft /></el-icon>
        <div class="title">{{ myYear }}年{{ myMonth }}月</div>
        <el-icon @click="handleRight"><ArrowRight /></el-icon>
      </div>
      <div class="week">
        <div>一</div>
        <div>二</div>
        <div>三</div>
        <div>四</div>
        <div>五</div>
        <div>六</div>
        <div>日</div>
      </div>
      <div class="day_case">
        <div v-for="(empty, index) in weekOffset" class="empty" :key="index"></div>
        <div class="day" v-for="(day, index) in daysInMonth" :key="index + weekOffset.length">
          <div @click="toggleDaySelection(index, day)" :class="{ selected: selectedDays[index] }" class="item_day">{{ day }}</div>
        </div>
      </div>
    </div>
    <div class="btn_case">
      <el-button type="primary" @click="selectAll(true)">全选</el-button>
      <el-button type="danger" @click="selectAll(false)">清空</el-button>
    </div>
  </div>
</template>  
  
<script setup lang="ts">
import { onMounted, ref, computed, watch, defineExpose } from "vue";
const emit = defineEmits(["handleCheckDay", "handleSearchDate"]);

const daysInMonth = ref<number[]>([]);
const weekOffset = ref<number[]>([]);
const currentMonth = ref<number>(new Date().getMonth() + 1); // 当前月份，从1开始
const currentYear = ref<number>(new Date().getFullYear()); // 当前年份
const selectedDays = ref<boolean[]>([]); // 选中状态的数组
const myYear = ref(); //当前年份
const myMonth = ref(); //当前月份
const activeDays = ref<any[]>([]); //当前选中天数

// 使用 watch 监听 count 的变化
watch(activeDays.value, (newValue, oldValue) => {
  emit("handleSearchDate", newValue);
});

//父组件传递参数
function handleSearchTimes(times) {
  times = times.map((item) => {
    // console.log(item.startTime.substring(0,4)); //年费
    // console.log(item.startTime.substring(5,7)); //月份
    // console.log(item.startTime.substring(8,10)); //日
    return {
      year: item.startTime.substring(0, 4),
      month: item.startTime.substring(5, 7),
      day: item.startTime.substring(8, 10),
    };
  });
  console.log(times);

  const seen = new Map();
  const uniqueData = []; //去重

  times.forEach((item: any) => {
    const key = `${item.year}-${item.month}-${item.day}`;
    if (!seen.has(key)) {
      seen.set(key, true);
      uniqueData.push(item);
    }
  });
  //控制是否回显显示日期
  // uniqueData.forEach(item=>{
  //   console.log(item.day.replace(/^0+/, ''));
  //   selectedDays.value[item.day.replace(/^0+/, '')] = true;
  // })

  console.log("uniqueData", uniqueData);
}
// 计算月份的天数和偏移量
const calculateMonthData = (year: number, month: number) => {
  const lastDay = new Date(year, month, 0).getDate(); // 当前月份的天数

  const firstDayOfWeek = new Date(year, month - 1, 0).getDay(); // 当前月份第一天的星期几（注意这里应该是1而不是0）
  myYear.value = year;
  myMonth.value = month;
  daysInMonth.value = Array.from({ length: lastDay }, (_, i) => i + 1);
  weekOffset.value = Array.from({ length: firstDayOfWeek }, (_, i) => i);
  selectedDays.value = Array(lastDay).fill(false); // 初始化选中状态数组
};

onMounted(() => {
  calculateMonthData(currentYear.value, currentMonth.value);
});

const handleLeft = () => {
  currentMonth.value = (currentMonth.value - 1 + 12) % 12; // 上一月，考虑跨年
  if (currentMonth.value === 0) {
    currentMonth.value = 12; // 如果变成0，则设为12（即上一年的12月）
    currentYear.value -= 1; // 同时年份减一
  }
  calculateMonthData(currentYear.value, currentMonth.value);
};

const handleRight = () => {
  if (currentMonth.value === 12) {
    currentYear.value += 1;
    currentMonth.value = 1;
  } else {
    currentMonth.value += 1;
  }
  calculateMonthData(currentYear.value, currentMonth.value);
};

// 切换日期的选中状态
const toggleDaySelection = (index: number, day) => {
  const isSelected = selectedDays.value[index];
  if (isSelected) {
    // 如果当前天数已被选中，则移除它
    const indexInActiveDays = activeDays.value.indexOf(day);

    // if (indexInActiveDays !== -1) {
    activeDays.value.splice(indexInActiveDays, 1);
    // }
    selectedDays.value[index] = false;
  } else {
    // 如果当前天数未被选中，则添加它
    if (!activeDays.value.includes(day)) {
      if (day < 10) {
        day = `0${day}`;
      }
      let str = `${myYear.value}-${myMonth.value}-${day}`;
      activeDays.value.push(str);
      emit("handleCheckDay", activeDays.value);
    }
    selectedDays.value[index] = true;
  }
};

// 全选功能
const selectAll = (status) => {
  // 将所有日期设置为选中状态（true）
  selectedDays.value = selectedDays.value.map(() => status);
  let data = [];
  data = data.concat(daysInMonth.value);
  data = data.map((item) => {
    return item < 10 ? `0${item}` : `${item}`;
  });
  data = data.map((item) => {
    return `${myYear.value}-${myMonth.value}-${item}`;
  });
  console.log(data);
  emit("handleCheckDay", data);
};
defineExpose({
  handleSearchTimes,
});
</script>  
  
<style lang="scss" scoped>
.btn_case {
  margin-top: 14px;
  display: flex;
  justify-content: flex-end;
}
.container {
  margin: 0 auto;
  .headerDate {
    border: 1px solid rgb(191, 187, 187);
    padding: 20px;
    .title_case {
      display: flex;
      justify-content: space-between;
      align-items: center;
      .title {
        font-size: 38rpx;
      }
    }
    .week {
      display: flex;
      justify-content: space-around;
      div {
        width: 14.28%; // 7天，所以每份是1/7≈14.28%
        text-align: center;
      }
    }
    .day_case {
      display: flex;
      flex-wrap: wrap;
      .empty,
      .day {
        width: 14.28%; // 同上
        text-align: center;
        padding: 14rpx 0; // 可选，为了美观添加一些内边距
        display: flex;
        justify-content: center;
        margin: 4px 0;
      }
      .day {
        border: 1rpx solid #ddd; // 可选，为了区分日期和空白，添加边框
        .item_day {
          width: 24px;
          height: 24px;
          cursor: pointer;
          user-select: none;
        }
        .selected {
          background-color: #007bff; // 选中状态的样式
          color: white;
          border-radius: 50%;
        }
      }
    }
  }
}
</style>
